![]() | |
|
|
|
To access the contents, click the chapter and section titles.
Bug Proofing Visual Basic: A Guide to Error Handling and Prevention
Self-TestMany of the ideas presented in this chapter cannot be easily demonstrated by example code. Pointing to a piece of code and saying it is the result of hasty work or too much emphasis on speed is difficult. Program Bad1 violates several of the more easily demonstrated guidelines presented in this chapter. The program, shown in Figure 1.3, generates a random list of numbers. When you enter a value in the Target field and click the Search button, the program uses a binary search to locate the item you entered in the list. The following code shows how program Bad1 works. Assume that this code has just been written near the beginning of the project, and that it has been accepted into the projects code library. You should be able to make several improvements. Appendix A, Self-Test Solutions, contains a revised version of this code with some suggested changes.
Option Explicit
Private Values(1 To 50) As Integer
Private Sub Form_Load()
Ready
End Sub
Private Sub Ready()
Dim i As Integer
Dim txt As String
Randomize
Values(1) = Int(Rnd * 10 + 1)
For i = 2 To 50
Values(i) = Values(i - 1) + Int(10 * Rnd + 1)
Next i
For i = 1 To 50
txt = txt & Format$(i, @@) & _
Format$(Values(i), @@@@) & vbCrLf
Next i
txtValues.Text = txt
End Sub
Private Sub CmdSearch_Click()
Dim i As Integer
i = BinarySearch(Values, CInt(txtTarget.Text))
lblPosition.Caption = Format$(i, @@) & _
Format$(Values(i), @@@@) & vbCrLf
End Sub
Public Function BinarySearch(list() As Integer, _
target As Integer) As Integer
Dim a As Integer
Dim b As Integer
Dim c As Integer
a = 1
c = 50
Do While a <= c
b = (c + a) / 2
If target = list(b) Then
BinarySearch = b
Exit Function
ElseIf target < list(b) Then
c = b - 1
Else
a = b + 1
End If
Loop
BinarySearch = 0
End Function
SummaryMental discipline is critical for effective programming. The following Bug Stoppers summarize concepts that are helpful for maintaining a bug-free attitude. Attitude is everything. Without the proper mindset, you may write thousands of lines of code very quickly, only to waste months of extra time debugging them. By coding more carefully, you can produce more working code in less time. You can control the code and not let deadlines and bugs control you.
|
|
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.
|